<template>
  <div class="register">
    <div class="title">欢迎注册</div>
    <van-form>
      <van-field
        v-model="username"
        label="用户名"
        size="large"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '用户名不能为空' }]"
      />
      <van-field
        v-model="password"
        type="password"
        label="密码"
        size="large"
        name="validator"
        placeholder="请输入密码"
        :rules="[
          { required: true, message: '密码不能为空' },
          { validator: validatePassword, message: '密码长度为六位' }
        ]"
      />
      <van-field
        v-model="password2"
        type="password2"
        size="large"
        label="重复密码"
        placeholder="请再次输入密码"
        :rules="[
          { required: true, message: '重复密码不能为空' },
          { validator: validatePassword2, message: '前后两次密码不一致' }
        ]"
      />
      <div style="margin-top: 16px">
        <van-button round block type="primary" @click="onRegister"> 注册</van-button>
      </div>
      <div class="footer">
        <span class="login" @click="goLogin">直接登录</span>
      </div>
    </van-form>
  </div>
</template>

<script>
import { getCurrentInstance, ref } from 'vue'
import router from '../router/index'
export default {
  setup() {
    const { proxy } = getCurrentInstance()
    const username = ref('')
    const password = ref('')
    const password2 = ref('')
    const validatePassword = (val) => /\d{6}/.test(val)

    const validatePassword2 = (val) => {
      console.log(val)
      if (val !== password.value) {
        return false
      } else {
        return true
      }
    }
    const onRegister = () => {
      if (username.value === '' || password2.value === '' || password.value != password2.value) {
        proxy.$toast.fail('请按规范输入')
        return
      }
      const data = {
        username: username.value,
        password: password.value,
        password2: password2.value
      }
      proxy.$toast.post('/register', data).then((res) => {
        console.log(res)
        proxy.$toast.success('注册成功')
      })
    }

    const goLogin = () => {
      router.push('/login')
    }

    return {
      username,
      password,
      password2,
      onRegister,
      goLogin,
      validatePassword,
      validatePassword2
    }
  }
}
</script>

<style>
.register {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #95e3e4;
  height: 100%;
}
.title {
  font-size: 1.75rem;
}
.van-form {
  height: 18.75rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.van-cell--large {
  margin: 0.65rem 0;
  border-radius: 8px;
}
.footer {
  color: #ccc;
  text-align: center;
  font-size: 0.85rem;
  padding: 0.625rem;
}
.login {
  color: #aaa;
  font-weight: bold;
}
</style>
